#!/bin/bash

cmd=kvm-xxx

function fatal
{
	echo "$cmd: $*" 1>&2 
	exit 1
}

function process
{
	ifdef=0
	comments=0
	err=/tmp/kvm-xxx.$$

	if [[ -n $1 ]]; then
		since="--since=\"$1 weeks ago\""
	fi

	for commit in `eval git log --format=%ct:%H $since | sort -n`; do
		hash=`echo $commit | cut -d: -f2`
		date=`echo $commit | cut -d: -f1`

		git checkout $hash > /dev/null 2> $err

		if [[ "$?" -ne 0 ]]; then
			fatal "unable to git checkout $hash: `cat $err`"
		fi

		files=`git ls-tree $hash | awk '{ print $4 }'`

		ifdef=`grep '#ifdef XXX' $files 2> /dev/null | \
		    grep -v '#endif' | wc -l`
		comments=`grep '* XXX' $files 2> /dev/null | \
		    grep -v '#endif' | wc -l`
		echo $date $ifdef $comments
	done

	rm $err 2> /dev/null

	now=`date +%s`

	if [[ $now -eq "s" ]]; then
		#
		# Seriously, WTF date(1)?  Can we try to suck less?!
		#
		now=`pfexec dtrace -q \
		    -n BEGIN'{trace(walltimestamp / 1000000000); exit(0)}'`

		if [[ $? -ne 0 ]]; then
			fatal "couldn't get current Unix time"
		fi
	fi

	echo $now $ifdef $comments
}

gpl=/tmp/kvm-xxx-$$.gpl
out=/tmp/kvm-xxx-$$.out

cat /dev/null > $out

if [[ ! -d .git ]]; then
	fatal "must be in the root directory of the repo"
fi

if [[ `uname -s` == "SunOS" ]]; then
	make clean
fi

if ! git checkout master > /dev/null 2>&1 ; then
	fatal "could not checkout master"
fi

echo "$cmd: processing all-time data..."
process > $out-all
echo "$cmd: processing data over last month..."
process 4 > $out-month
echo "$cmd: processing data over last week..."
process 1 > $out-week

git checkout master > /dev/null 2>&1

cat > $gpl <<EOF
set term postscript "Helvetica" 12
set output "kvm-xxx.ps"
set size 1,1
set noborder

set timefmt "%s"
set xdata time
set format x "%m/%d"
set yrange [0:]
set ylabel "Occurences of XXX"
set xlabel "Date"

set title "Number of XXXs in KVM"
plot "$out-all" using 1:2 with lines title "#ifdef XXX", \
    "$out-all" using 1:3 with lines title "Commented XXX"
 
set format x "%m/%d"
set title "Number of XXXs in KVM over the past month"
plot "$out-month" using 1:2 with lines title "#ifdef XXX", \
    "$out-month" using 1:3 with lines title "Commented XXX"

set format x "%m/%d\n%H:%M"
set title "Number of XXXs in KVM over the past week"
plot "$out-week" using 1:2 with lines title "#ifdef XXX", \
    "$out-week" using 1:3 with lines title "Commented XXX"

EOF

if gnuplot $gpl ; then
	echo "$cmd: done; output is kvm-xxx.ps"
	rm $gpl $out*
else
	echo "can't plot; gnuplot control file is $gpl"
fi

